<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import dayjs, { type Dayjs } from 'dayjs';
import { fetchHolidaysByCurrency } from '@/service/api/holiday';

// 假日数据接口
interface HolidayData {
  id?: number;
  currencyCode: string;
  holidayDate: string;
  dayType: number; // 0-假日，1-调休工作日
  holidayNameEn?: string;
  createTime?: string;
  updateTime?: string;
}

interface Emits {
  (e: 'close'): void;
}

interface Props {
  open: boolean;
  currencyCode: string;
}

defineOptions({
  name: 'ViewHolidayModal'
});

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const loading = ref(false);
const holidayData = ref<HolidayData[]>([]);
const selectedDate = ref<Dayjs>(dayjs());

const visible = computed({
  get() {
    return props.open;
  },
  set(value) {
    if (!value) {
      emit('close');
    }
  }
});

// 假日日期集合（只包含假日，不包含调休工作日）
const holidayDates = computed(() => {
  return new Set(
    holidayData.value
      .filter(holiday => holiday.dayType === 0) // 只包含假日
      .map(holiday => {
        // 处理后端返回的ISO日期格式，转换为YYYY-MM-DD格式
        const date = new Date(holiday.holidayDate);
        return dayjs(date).format('YYYY-MM-DD');
      })
  );
});

// 调休工作日日期集合
const workdayDates = computed(() => {
  return new Set(
    holidayData.value
      .filter(holiday => holiday.dayType === 1) // 只包含调休工作日
      .map(holiday => {
        // 处理后端返回的ISO日期格式，转换为YYYY-MM-DD格式
        const date = new Date(holiday.holidayDate);
        return dayjs(date).format('YYYY-MM-DD');
      })
  );
});

// 判断是否为手动设置的假日
function isManualHoliday(date: Dayjs): boolean {
  const dateStr = date.format('YYYY-MM-DD');
  return holidayDates.value.has(dateStr);
}

// 判断是否为调休工作日
function isWorkday(date: Dayjs): boolean {
  const dateStr = date.format('YYYY-MM-DD');
  return workdayDates.value.has(dateStr);
}

// 获取假日数据
async function getHolidayData() {
  if (!props.currencyCode) return;

  loading.value = true;
  try {
    const { data: resData, error } = await fetchHolidaysByCurrency(props.currencyCode);
    if (resData) {
      holidayData.value = resData;
    } else {
      console.error('获取假日数据失败:', error);
      holidayData.value = [];
    }
  } catch (error) {
    console.error('获取假日数据失败:', error);
    holidayData.value = [];
  } finally {
    loading.value = false;
  }
}

function handleClose() {
  visible.value = false;
  selectedDate.value = dayjs();
}

watch(
  () => props.open,
  newVal => {
    if (newVal && props.currencyCode) {
      getHolidayData();
    }
  }
);

watch(
  () => props.currencyCode,
  newVal => {
    if (newVal && props.open) {
      getHolidayData();
    }
  }
);
</script>

<template>
  <AModal v-model:open="visible" :title="`${currencyCode} 假日查看`" width="800px" @cancel="handleClose">
    <template #footer>
      <AButton @click="handleClose">关闭</AButton>
    </template>

    <div class="space-y-4">
      <!-- 日历查看 -->
      <ACard size="small" title="假日日历">
        <ASpin :spinning="loading">
          <div class="calendar-wrapper">
            <ACalendar v-model:value="selectedDate" :fullscreen="false">
              <template #dateFullCellRender="{ current }">
                <div
                  class="date-cell"
                  :class="{
                    'holiday-cell': isManualHoliday(current),
                    'workday-cell': isWorkday(current),
                    'normal-cell': !isManualHoliday(current) && !isWorkday(current)
                  }"
                >
                  <div class="date-number">{{ current.date() }}</div>
                  <div v-if="isWorkday(current)" class="workday-mark">班</div>
                  <div v-if="isManualHoliday(current)" class="holiday-mark">休</div>
                </div>
              </template>
            </ACalendar>
          </div>

          <!-- 说明信息 -->
          <div class="operation-tips">
            <AAlert
              message="图例说明"
              description="灰色背景表示普通工作日，绿色背景表示假日，红色背景表示调休工作日。此为只读模式，如需修改请使用修改假日功能。"
              type="info"
              show-icon
            />
          </div>
        </ASpin>
      </ACard>
    </div>
  </AModal>
</template>

<style scoped>
.space-y-4 > * + * {
  margin-top: 16px;
}

.calendar-wrapper {
  margin-bottom: 16px;
}

.date-cell {
  position: relative;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  margin: 0 auto;
  pointer-events: none; /* 禁用点击事件，只读模式 */
}

.holiday-cell {
  background-color: #f2ffea;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.workday-cell {
  background-color: #ffedf1;
  color: #c41a1a;
  border: 1px solid #eb8f9d;
}

.normal-cell {
  background-color: #eaeaea5b;
  color: #000000;
}

.date-number {
  font-size: 14px;
  font-weight: 500;
}

.workday-mark {
  position: absolute;
  top: 1px;
  right: 0px;
  font-size: 10px;
  color: #c41a36;
  font-weight: bold;
  background-color: #ffffff00;
  border-radius: 2px;
  padding: 0 2px;
  line-height: 1;
}

.holiday-mark {
  position: absolute;
  top: 1px;
  right: 0px;
  font-size: 10px;
  color: #52c41a;
  font-weight: bold;
  background-color: #ffffff00;
  border-radius: 2px;
  padding: 0 2px;
  line-height: 1;
}

.operation-tips {
  margin-top: 16px;
}

:deep(.ant-picker-calendar-date-content) {
  height: 60px;
}

:deep(.ant-picker-cell-in-view.ant-picker-cell-selected .ant-picker-calendar-date) {
  background-color: #e6f7ff;
  border-color: #1890ff;
}
</style>
